<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 名片维护系统</title>
    <!-- <link rel="stylesheet" th:href="@{/css/styles.css}"> -->
    <!-- Removed Bootstrap CDN links -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <!-- <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script> -->
    <style>
        /* Reset and Base Styles (Copied from index.html, can be externalized later) */
        :root {
            --primary-color: #3498db; /* Bright Blue */
            --primary-hover-color: #2980b9;
            --sidebar-bg: #2c3e50; /* Dark Blue/Grey */
            --sidebar-text-color: #ecf0f1;
            --sidebar-active-link-bg: #34495e;
            --sidebar-active-link-border: var(--primary-color);
            --content-bg: #f4f6f9; /* Very Light Grey */
            --text-color: #333;
            --text-muted-color: #777;
            --card-bg: #ffffff;
            --card-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            --border-color: #e0e0e0;
            --success-color: #2ecc71;
            --error-color: #e74c3c;
            --info-color: #3498db;
            --warning-color: #f39c12;
            --font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: var(--font-family);
            background-color: var(--content-bg);
            color: var(--text-color);
            line-height: 1.6;
            display: flex;
        }

        a {
            text-decoration: none;
            color: var(--primary-color);
        }

        a:hover {
            color: var(--primary-hover-color);
        }

        /* Admin Container */
        .admin-container {
            display: flex;
            width: 100%;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 260px;
            background-color: var(--sidebar-bg);
            color: var(--sidebar-text-color);
            padding: 20px 0;
            display: flex;
            flex-direction: column;
            flex-shrink: 0;
        }

        .sidebar-title {
            font-size: 1.5em;
            font-weight: 600;
            text-align: center;
            padding: 0 20px 20px 20px;
            margin-bottom: 20px;
            border-bottom: 1px solid rgba(236, 240, 241, 0.1);
            color: var(--sidebar-text-color);
        }

        .menu-list {
            list-style-type: none;
        }

        .menu-item .menu-link {
            display: block;
            padding: 15px 25px;
            color: var(--sidebar-text-color);
            font-size: 1em;
            transition: background-color 0.3s ease, color 0.3s ease, border-left 0.3s ease;
            border-left: 3px solid transparent;
            text-decoration: none; /* 添加这行去除下划线 */
        }

        .menu-item .menu-link .fa {
            margin-right: 10px;
            width: 20px; /* Align icons */
            text-align: center;
        }

        .menu-item .menu-link:hover {
            background-color: var(--sidebar-active-link-bg);
            border-left-color: var(--primary-hover-color);
            color: #fff;
        }

        .menu-item .menu-link.active {
            background-color: var(--sidebar-active-link-bg);
            border-left-color: var(--sidebar-active-link-border);
            font-weight: 600;
            color: #fff;
        }

        /* Main Content */
        .main-content {
            flex-grow: 1;
            background-color: var(--content-bg);
            padding: 0;
            display: flex;
            flex-direction: column;
        }

        /* Header */
        .header {
            background-color: var(--card-bg);
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            border-bottom: 1px solid var(--border-color);
        }

        .header-title {
            font-size: 1.8em;
            font-weight: 600;
            color: var(--text-color);
        }

        .logout-button {
            background-color: var(--primary-color);
            color: white;
            padding: 8px 15px;
            border-radius: 5px;
            font-size: 0.9em;
            transition: background-color 0.3s ease;
            border: none;
            cursor: pointer;
        }

        .logout-button:hover {
            background-color: var(--primary-hover-color);
            color: white;
        }

        .logout-button .fa {
            margin-right: 5px;
        }

        /* Content Area */
        .content-area { /* General wrapper for content below header */
            padding: 30px;
            flex-grow: 1;
        }

        /* Message Styles */
        .message {
            padding: 15px 20px;
            margin-bottom: 20px;
            border-radius: 5px;
            font-size: 0.95em;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .message .fa {
            margin-right: 10px;
            font-size: 1.2em;
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* Table Styles specific to user-management */
        .table-container {
            background-color: var(--card-bg);
            border-radius: 8px;
            box-shadow: var(--card-shadow);
            overflow-x: auto;
            padding: 20px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th,
        .table td {
            padding: 12px 15px; /* Slightly reduced padding for denser table */
            text-align: left;
            border-bottom: 1px solid var(--border-color);
            font-size: 0.9em;
        }

        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: var(--text-muted-color);
            text-transform: uppercase;
            font-size: 0.8em;
            letter-spacing: 0.5px;
        }

        .table tbody tr:hover {
            background-color: #f1f3f5;
        }

        .table tbody tr:last-child td {
            border-bottom: none;
        }

        .table td .status-locked {
            color: var(--error-color);
            font-weight: 500;
        }

        .table td .status-normal {
            color: var(--success-color);
            font-weight: 500;
        }

        .table-button {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            color: white;
            font-size: 0.85em;
            transition: background-color 0.2s ease, opacity 0.2s ease;
            margin-right: 5px;
            text-transform: capitalize;
        }
        .table-button .fa {
            margin-right: 4px;
        }

        .table-button:last-child {
            margin-right: 0;
        }

        .table-button:hover {
            opacity: 0.85;
        }

        .table-button.lock {
            background-color: var(--warning-color);
        }
        .table-button.unlock {
            background-color: var(--success-color);
        }
        .table-button.edit { /* For reset password */
            background-color: var(--info-color);
        }
        .table-button.promote {
            background-color: #9b59b6; /* Purple */
        }

    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <h2 class="sidebar-title">名片维护系统</h2>
            <ul class="menu-list">
                <li class="menu-item">
                    <a class="menu-link" href="/admin/index"><i class="fa fa-home"></i>首页</a>
                </li>
                <li class="menu-item">
                    <a class="menu-link active" href="/admin/user-management"><i class="fa fa-users"></i>用户管理</a>
                </li>
                <li class="menu-item">
                    <a class="menu-link" href="/admin/usergroup"><i class="fa fa-user-circle"></i>用户组管理</a>
                </li>
                <li class="menu-item">
                    <a class="menu-link" href="/admin/change-password"><i class="fa fa-key"></i>修改密码</a>
                </li>
            </ul>
        </div>

        <!-- 主要内容 -->
        <div class="main-content">
            <div class="header">
                <h2 class="header-title">用户管理</h2>
                <a class="logout-button" href="/admin/logout"><i class="fa fa-sign-out"></i>退出登录</a>
            </div>

            <div class="content-area">
            <!-- 消息提示 -->
                <div class="message success" id="success-message" style="display: none;" th:if="${successMessage}">
                    <i class="fa fa-check-circle"></i> <span th:text="${successMessage}"></span>
                </div>
                <div class="message error" id="error-message" th:style="${errorMessage != null ? 'display: flex;' : 'display: none;'}" th:unless="${errorMessage == null}">
                    <i class="fa fa-times-circle"></i> <span th:text="${errorMessage}"></span>
                </div>

            <!-- 用户列表 -->
            <div class="table-container">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                                <th><i class="fa fa-user"></i> 用户名</th>
                                <th><i class="fa fa-envelope"></i> 邮箱</th>
                                <th><i class="fa fa-shield"></i> 角色</th>
                                <th><i class="fa fa-calendar"></i> 创建时间</th>
                                <th><i class="fa fa-info-circle"></i> 状态</th>
                                <th><i class="fa fa-cogs"></i> 操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr th:each="user : ${userList}">
                                <td th:text="${user.id != null ? user.id : '-'}">1</td>
                                <td th:text="${user.username != null ? user.username : '-'}">用户名</td>
                                <td th:text="${user.email != null ? user.email : '-'}">邮箱</td>
                                <td th:text="${user.role != null ? user.role : '-'}">角色</td>
                                <td th:text="${user.createTime != null ? #dates.format(user.createTime, 'yyyy-MM-dd HH:mm:ss') : '-'}">创建时间</td>
                                <td>
                                    <span th:if="${user.accountLocked != null && user.accountLocked}" class="status-locked"><i class="fa fa-lock"></i> 已锁定</span>
                                    <span th:if="${user.accountLocked != null && !user.accountLocked}" class="status-normal"><i class="fa fa-unlock"></i> 正常</span>
                                    <span th:if="${user.accountLocked == null}" class="text-muted">-</span>
                                </td>
                                <td>
                                    <button th:if="${user.id != null && user.accountLocked != null && !user.accountLocked}" class="table-button lock" th:onclick="|lockUser(${user.id}, true)|"><i class="fa fa-lock"></i> 锁定</button>
                                    <button th:if="${user.id != null && user.accountLocked != null && user.accountLocked}" class="table-button unlock" th:onclick="|lockUser(${user.id}, false)|"><i class="fa fa-unlock-alt"></i> 解锁</button>
                                    <button class="table-button edit" th:attr="onclick=|resetPassword('${user.email}')|" th:if="${user.email != null}"><i class="fa fa-key"></i> 重置密码</button>
                                    <button th:if="${user.id != null && user.role != null && user.role != 'ADMIN'}" class="table-button promote" th:onclick="|promoteUser(${user.id})|"><i class="fa fa-user-plus"></i> 提升</button>
                            </td>
                        </tr>
                            <tr th:if="${userList == null || #lists.isEmpty(userList)}">
                                <td colspan="7" style="text-align: center; padding: 20px; color: var(--text-muted-color);">暂无用户数据</td>
                        </tr>
                    </tbody>
                </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 锁定/解锁用户
        function lockUser(userId, locked) {
            if (!confirm(locked ? '确定要锁定该用户吗？' : '确定要解锁该用户吗？')) {
                return;
            }

            fetch('/admin/lock-user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'userId=' + userId + '&locked=' + locked
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess(data.message);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showError(data.message);
                }
            })
            .catch(error => {
                showError('服务器通讯错误，请稍后再试。');
                console.error('Lock User Error:', error);
            });
        }

        // 重置密码
        function resetPassword(email) {
            if (!email) {
                showError('用户邮箱信息缺失，无法重置密码。');
                return;
            }

            if (!confirm('确定要重置该用户的密码吗？临时密码将发送到用户邮箱。')) {
                return;
            }

            fetch('/admin/reset-password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'email=' + encodeURIComponent(email)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess(data.message);
                } else {
                    showError(data.message || '密码重置失败，请检查邮箱或联系管理员。');
                }
            })
            .catch(error => {
                showError('服务器通讯错误，请稍后再试。');
                console.error('Reset Password Error:', error);
            });
        }

        // 提升为管理员
        function promoteUser(userId) {
            if (!confirm('确定要将该用户提升为管理员吗？此操作不可逆。')) {
                return;
            }

            fetch('/admin/promote-user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'userId=' + userId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccess(data.message);
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showError(data.message || '提升用户权限失败。');
                }
            })
            .catch(error => {
                showError('服务器通讯错误，请稍后再试。');
                console.error('Promote User Error:', error);
            });
        }

        const successMessageElement = document.getElementById('success-message');
        const errorMessageElement = document.getElementById('error-message');

        function showSuccess(message) {
            if (successMessageElement) {
                const span = successMessageElement.querySelector('span') || successMessageElement;
                span.textContent = message;
                successMessageElement.style.display = 'flex'; // Use flex for icon alignment
            }
            if (errorMessageElement) errorMessageElement.style.display = 'none';

            setTimeout(() => {
                if (successMessageElement) successMessageElement.style.display = 'none';
            }, 3000);
        }

        function showError(message) {
            if (errorMessageElement) {
                const span = errorMessageElement.querySelector('span') || errorMessageElement;
                span.textContent = message;
                errorMessageElement.style.display = 'flex'; // Use flex for icon alignment
            }
            if (successMessageElement) successMessageElement.style.display = 'none';

            setTimeout(() => {
                if (errorMessageElement) errorMessageElement.style.display = 'none';
            }, 5000); // Error messages stay a bit longer
        }

        // If there are pre-rendered messages from Thymeleaf, ensure they are shown correctly
        document.addEventListener('DOMContentLoaded', () => {
            if (errorMessageElement && errorMessageElement.textContent.trim() !== '' && errorMessageElement.style.display !== 'none'){
                 // Ensure the span is correctly populated if not done by Thymeleaf directly
                const currentText = errorMessageElement.textContent.trim();
                const iconElement = errorMessageElement.querySelector('i');
                errorMessageElement.innerHTML = ''; // Clear it
                if(iconElement) errorMessageElement.appendChild(iconElement); // Re-add icon
                const span = document.createElement('span');
                span.textContent = ' ' + currentText; // Add space after icon
                errorMessageElement.appendChild(span);
                errorMessageElement.style.display = 'flex';
            }
             if (successMessageElement && successMessageElement.textContent.trim() !== '' && successMessageElement.style.display !== 'none'){
                const currentText = successMessageElement.textContent.trim();
                const iconElement = successMessageElement.querySelector('i');
                successMessageElement.innerHTML = ''; // Clear it
                if(iconElement) successMessageElement.appendChild(iconElement); // Re-add icon
                const span = document.createElement('span');
                span.textContent = ' ' + currentText; // Add space after icon
                successMessageElement.appendChild(span);
                successMessageElement.style.display = 'flex';
            }
        });

    </script>
</body>
</html>

